package com.wind.fragment;

import android.content.pm.ActivityInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wind.adapter.UpdateListAdapter;
import com.wind.adapter.VideoRecyclerViewAdapter;
import com.wind.base.BaseFragment;
import com.wind.base.VideoBean;
import com.wind.beans.updateListBean;
import com.debug.soblogin.R;
import com.wind.utils.DataUtil;
import com.wind.utils.OnItemChildClickListener;
import com.wind.utils.Tag;
import com.wind.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import xyz.doikki.videocontroller.StandardVideoController;
import xyz.doikki.videocontroller.component.CompleteView;
import xyz.doikki.videocontroller.component.ErrorView;
import xyz.doikki.videocontroller.component.GestureView;
import xyz.doikki.videocontroller.component.TitleView;
import xyz.doikki.videocontroller.component.VodControlView;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.player.VideoViewManager;


public class StarFragment extends BaseFragment implements OnItemChildClickListener {

    private ArrayList<updateListBean> mData;
    private ArrayList<String> dateList;
    private ArrayList<String> contentList;
    private RecyclerView mList;
    private RecyclerView mVideoList;
    private UpdateListAdapter mAdapter;

    private ArrayList<VideoBean> mVideos;
    protected VideoView mVideoView;
    protected StandardVideoController mController;
    protected ErrorView mErrorView;
    protected CompleteView mCompleteView;
    protected TitleView mTitleView;

    /**
     * 当前播放的位置
     */
    protected int mCurPos = -1;
    /**
     * 上次播放的位置，用于页面切回来之后恢复播放
     */
    protected int mLastPos = mCurPos;
    private LinearLayoutManager mLinearLayoutManager;
    private List<VideoBean> videoList;
    private VideoRecyclerViewAdapter mVideoAdapter;

    public StarFragment() {
    }

    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_star, container, false);
    }

    @Override
    protected void initView(View rootView) {

        super.initView(rootView);
        mVideoList = rootView.findViewById(R.id.video_list);
        initVideoView();
        videoList = DataUtil.getVideoList();
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        mVideoList.setLayoutManager(mLinearLayoutManager);
        mVideoAdapter = new VideoRecyclerViewAdapter(videoList);
        mVideoAdapter.setOnItemChildClickListener(this);
        mVideoList.setAdapter(mVideoAdapter);
        mVideoList.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                FrameLayout playerContainer = view.findViewById(R.id.player_container);
                View v = playerContainer.getChildAt(0);
                if (v != null && v == mVideoView && !mVideoView.isFullScreen()) {
                    releaseVideoView();
                }
            }
        });





//
//
//        //下面是下面的处理
        mList = rootView.findViewById(R.id.update_list);
        mData = new ArrayList<>();
        dateList = new ArrayList<>();
        contentList = new ArrayList<>();
        //TODO：添加更新日志
        addItem("2022-03-03", "大海页面UI修改，新增摸鱼瞬间跳转按钮。星辰页面UI调整。我的界面新增建议按钮，进入后可以给作者提出建议。");
        addItem("2022-02-23", "星辰页面新增视频在线播放功能。修改部分UI。修复frameLayout退出后进入重叠问题。");
        addItem("2022-02-22", "疾风App第一个beta版本正式发布，支持浏览网站大部分内容。注册登录，评论等模块正在紧张coding！敬请期待😊！");
        addItem("2022-02-21", "修改文章详情内容加载逻辑，使用更加年轻化的VUE框架。");
        addItem("2022-02-20", "修复若干显示BUG，并修改部分UI。");
        addItem("2022-02-19", "增加app更新模块，并开始正式支持内置升级！");
        addItem("2022-02-18", "真是令人激动的时刻。疾风APP1.0第一次开始提交代码，并开启随缘更新模式。");

        for (int i = 0; i < dateList.size(); i++) {
            updateListBean updateListBean = new updateListBean();
            updateListBean.date=dateList.get(i);
            updateListBean.content=contentList.get(i);
            mData.add(updateListBean);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        mList.setLayoutManager(layoutManager);

        //创建适配器
        mAdapter = new UpdateListAdapter(mData);
        //设置到recycle里面去
        mList.setAdapter(mAdapter);
    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    protected void pause() {
        releaseVideoView();
    }

    @Override
    public void onResume() {
        super.onResume();
        resume();
    }

    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    protected void resume() {
        if (mLastPos == -1)
            return;

        //恢复上次播放的位置
        startPlay(mLastPos);
    }
    /**
     * PrepareView被点击
     */

    @Override
    public void onItemChildClick(int position) {
        startPlay(position);
    }

    /**
     * 开始播放
     * @param position 列表位置
     */
    protected void startPlay(int position) {
        if (mCurPos == position) return;
        if (mCurPos != -1) {
            releaseVideoView();
        }
        System.out.println("start----------->" + position);
        VideoBean videoBean = videoList.get(position);
        mVideoView.setUrl(videoBean.getUrl());
        mTitleView.setTitle(videoBean.getTitle());
        View itemView = mLinearLayoutManager.findViewByPosition(position);
        if (itemView == null) return;
        VideoRecyclerViewAdapter.VideoHolder viewHolder = (VideoRecyclerViewAdapter.VideoHolder) itemView.getTag();
        //把列表中预置的PrepareView添加到控制器中，注意isDissociate此处只能为true, 请点进去看isDissociate的解释
        mController.addControlComponent(viewHolder.mPrepareView, true);
        Utils.removeViewFormParent(mVideoView);
        viewHolder.mPlayerContainer.addView(mVideoView, 0);
        //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        getVideoViewManager().add(mVideoView, Tag.LIST);
        mVideoView.start();
        mCurPos = position;

    }
    protected VideoViewManager getVideoViewManager() {
        return VideoViewManager.instance();
    }
    private void releaseVideoView() {
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
        if(getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mCurPos = -1;
    }

    protected void initVideoView() {
        mVideoView = new VideoView(Objects.requireNonNull(getActivity()));
        mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    Utils.removeViewFormParent(mVideoView);
                    mLastPos = mCurPos;
                    mCurPos = -1;
                }
            }
        });
        mController = new StandardVideoController(Objects.requireNonNull(getActivity()));
        mErrorView = new ErrorView(getActivity());
        mController.addControlComponent(mErrorView);
        mCompleteView = new CompleteView(getActivity());
        mController.addControlComponent(mCompleteView);
        mTitleView = new TitleView(getActivity());
        mController.addControlComponent(mTitleView);
        mController.addControlComponent(new VodControlView(getActivity()));
        mController.addControlComponent(new GestureView(getActivity()));
        mController.setEnableOrientation(true);
        mVideoView.setVideoController(mController);
    }
    private void addItem(String date, String content) {
        dateList.add(date);
        contentList.add(content);
    }
}

